package student.aistar.day15.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * 拿到线程之后的结果
 *          Callable + FutureTask -> 线程执行的结果
 */
public class CallableDemo {

}

class C1 implements Callable<Integer>{

    public static void main(String[] args) {
        System.out.println("main-begin...");
        Callable<Integer> c = new C1();
        //FutureTask - 异步任务
        FutureTask<Integer> task = new FutureTask<>(c);
        //利用异步任务来构建Thread对象
        Thread t = new Thread(task);
        t.start();
        System.out.println("线程已经启动了");


        try {
            //拿线程计算的结果
            //get()方法一定是要等到线程执行结束之后 - 才会停止
            System.out.println("result: " + task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //main线程也是要等到get()走完
        System.out.println(Thread.currentThread().getName() + "-main-end");
    }

    @Override
    public Integer call() throws Exception {
        int total = 0;
        for (int i = 0; i <= 100; i++) {
            total += i;
        }

        //故意模拟一个比较费时的任务
        Thread.sleep(1000);
        return total;
    }
}